# Copyright 2018 Maco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import configparser
import logging

ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))


def get_conf_path():
    '''
    Check config.conf file path
    '''
    file_path = os.path.join(ROOT_PATH, 'config.conf')
    if not os.path.exists(file_path):
        raise IOError('The \'{0}\' does not exist.'.format(file_path))
    return file_path


def get_option(section, option, default=None, ignore=True, boolean=False):
    '''
    get config.conf option
    :param section:
    :param option:
    :param default: default value
    :param ignore: ignore error output
    :param boolean: convert boolean
    Return: option value or default value
    '''
    conf = configparser.ConfigParser()
    try:
        conf.read(get_conf_path())
        val = conf.get(section, option)
        if not val:
            return default
        else:
            if boolean and val.lower() in ('false', '0'):
                val = False
            return val
    except configparser.Error as err:
        if not ignore:
            logging.warn(err.message)
        return default


def get_bool_opt(section, option, default=False, ignore=True):
    '''
    Return boolean result.
    '''
    result = get_option(section, option, default=None, ignore=ignore)
    if not result:
        return default
    if result.lower() in ('false', '0'):
        return False
    return True


def get_int_opt(section, option, default=None, ignore=True):
    '''
    Return int result or None(if not found and default=None).
    '''
    result = get_option(section, option, default=None, ignore=ignore)
    if not result:
        return default
    try:
        return int(result)
    except ValueError:
        return default


def set_option(section, option, value):
    '''
    Update config.conf value
    '''
    conf = configparser.ConfigParser()
    try:
        conf.read(get_conf_path())
        conf.set(section, option, value)
        conf.write(open(get_conf_path(), 'r+'))
    except configparser.Error as err:
        logging.error(err.message)
        raise ValueError(err.message)


def get_server_name(default='TornadoServer'):
    '''Return server name.'''
    return get_option('base', 'name', default)


def get_process_num():
    '''Return process number'''
    return get_int_opt('base', 'processes', 1)


def get_language():
    '''Return config.conf default language, default en_US'''
    return get_option('base', 'language', 'en_US')


if __name__ == '__main__':
    print(get_int_opt('base', 'port', 1111))
    if get_option('base', 'allow_jsonp', boolean=True):
        print('true')
    else:
        print('false')
